<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {
            position: absolute;
            display: block;
            left: 0;
            width: 150px;
            height: 150px;
            margin-top: 300px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button class="btn500">点击到500</button>
    <button class="btn800">点击到800</button>
    <div></div>
    <span>点击移动</span>
    <script>
        // 封装函数
        function animate(obj, target, callback) {
            clearInterval(obj.timer);
            // 解决开启太多定时器的bug
            obj.timer = setInterval(function () {
                // 步长值写在定时器里，并避免小数
                // var step = Math.ceil(target - obj.offsetLeft) / 10;
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer);
                    // 回调函数写在定时器结束里面
                    if (callback) {
                        callback();
                    }
                }
                // 把加1 的步长值改为缓存的步长
                obj.style.left = obj.offsetLeft + step + 'px';
            }, 15);
        }
        var div = document.querySelector('div');
        var span = document.querySelector('span');
        var btn500 = document.querySelector('.btn500');
        var btn800 = document.querySelector('.btn800');
        // 调用函数
        animate(div, 500);
        btn500.addEventListener('click', function () {
            animate(span, 500);
        });
        btn800.addEventListener('click', function () {
            animate(span, 800, function () {
                span.style.backgroundColor = 'blue';
            });
        })
    </script>
</body>

</html>